package cn.jaye.fabric.common.aspect;

import cn.jaye.fabric.common.exception.ServiceException;
import cn.jaye.fabric.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Jaye on 2017/10/17.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @Value("${spring.application.name}")
    private String applicationName;

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public String serviceException(ServiceException se) throws Exception {
        return ResultUtil.error(se.getCode(), se.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public String exception(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
        logger.error("[SYSTEM ERROR]", e);
        response.sendRedirect(request.getContextPath() + "/500");
        return null;
    }

}
